package com.example.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

import com.alibaba.fastjson.JSONObject;
import com.example.adapter.AsyAdapter;
import com.example.adapter.BannerAdapter;
import com.example.adapter.ViewPagerAdapter;
import com.example.bean.Banner;
import com.example.bean.Home;
import com.example.config.UrlsConfig;
import com.example.fruit.R;
import com.felipecsl.asymmetricgridview.library.Utils;
import com.felipecsl.asymmetricgridview.library.model.AsymmetricItem;
import com.felipecsl.asymmetricgridview.library.widget.AsymmetricGridView;
import com.felipecsl.asymmetricgridview.library.widget.AsymmetricGridViewAdapter;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment {

    private Home home;
    @ViewInject(R.id.listVIewId)
    private ListView listView;
    private HttpUtils httpUtils;
    private BitmapUtils bUtils;
    private ViewGroup topView;
    private List<Banner> data = new ArrayList<Banner>();
    private BannerAdapter homeBannerAdapter;
    private ViewPager viewPager;
    private List<ImageView> imageViews;
    private Handler handler = new Handler();
    private GridView gv;
    private RelativeLayout re;
    private  ListView topListView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        httpUtils = new HttpUtils();
        bUtils = new BitmapUtils(getActivity());

        topView = (LinearLayout) getActivity()
                .getLayoutInflater()
                .inflate(R.layout.view_tops, null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View views = inflater.inflate(R.layout.fragment_first, container, false);
        ViewUtils.inject(this, views);
        intiview();
        loadData();

        return views;


    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


    }

    private void intiview() {

        homeBannerAdapter = new BannerAdapter(getActivity(), data, bUtils);
        listView.setOnScrollListener(new PauseOnScrollListener(bUtils, true, false));
        homeBannerAdapter = new BannerAdapter(getActivity(), data, bUtils);

        listView.addHeaderView(topView);

        listView.setAdapter(homeBannerAdapter);
    }


    private ViewGroup getHeaderView(Home home) {

        showRotation(topView, home);
        showGrideView(topView);
//        showmixProduct(topView, home);
        showTopBanner(topView, home);

        showmixProduct2(topView, home);


        return topView;
    }

    private void showmixProduct2(ViewGroup topView, Home home) {
        re= (RelativeLayout) topView.findViewById(R.id.ReId);
        ImageView img1 = (ImageView) topView.findViewById(R.id.image1id);
        ImageView img2 = (ImageView) topView.findViewById(R.id.image2id);
        ImageView img3 = (ImageView) topView.findViewById(R.id.image3id);
        ImageView img4 = (ImageView) topView.findViewById(R.id.image4id);
        ImageView img5 = (ImageView) topView.findViewById(R.id.image5id);
       ImageView img6 = (ImageView) topView.findViewById(R.id.image6id);
        ImageView[] imageViews = {img1,img2,img3,img4,img5,img6};

        for(int i = 0;i<imageViews.length;i++){

            bUtils.display(imageViews[i], home.getMix_product_banner().get(i).getPhoto());

        }

    }


    private void loadData() {
        RequestParams params = getRquestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, UrlsConfig.FIRST_PAGE, params, new RequestCallBack<String>() {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                //获得服务器返回的json数据
                String result = responseInfo.result;
                home = JSONObject.parseObject(result, Home.class);
                if (home != null) {
                    if (home.getBanner() != null && home.getBanner().size() > 0) {
                        data.addAll(home.getBanner());
                        Log.i("info","yyy"+data);
                        homeBannerAdapter.notifyDataSetChanged();
                    }


                }

                Log.i("info", "1111");

                Log.i("info", "1112");

                getHeaderView(home);


            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }


    private void showTopBanner(View topView, Home home) {
        Log.i("info", "1114");
        topListView = (ListView) topView
                .findViewById(R.id.topBannerId);


        topListView.setDividerHeight(10);
        Log.i("info", "1115");
        BannerAdapter hAdapter =
                new BannerAdapter(getActivity(),
                        home.getTop_banner(), bUtils);

        topListView.setAdapter(hAdapter);
        data.addAll(home.getTop_banner());
        hAdapter.notifyDataSetChanged();


    }

    private void showmixProduct(View topView, Home home) {

        AsymmetricGridView listView =
                (AsymmetricGridView) topView
                        .findViewById(R.id.asymmetric_gridView);

        // Choose your own preferred column width
        listView.setRequestedColumnWidth(Utils.dpToPx(getActivity(), 100));
        List<String> items = new ArrayList<String>();
        for (Banner b:home.getMix_product_banner()){
        items.add(b.getPhoto());

        }
        AsymmetricGridViewAdapter adapter =
                new AsymmetricGridViewAdapter(getActivity(), listView,
                        new AsyAdapter(getActivity(), items));

        listView.setAdapter(adapter);

        //Supports resetting and appending more elements into the adapter:


// Will append more items at the end of the adapter.
//        listView.getAdapter().appendItems(moreItems);

// resetting the adapter items. Will clear the adapter
//
        //      listView.getAdapter().setItems(items);
        //Toggle to enable/disable reordering of elements to better fill the grid


// Setting to true will move items up and down to better use the space
// Defaults to false.
//        listView.setAllowReordering(true);
    }

    private void showGrideView(View topView) {

        List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
        for (int i = 1; i < 9; i++) {
            Map<String, Object> item = new HashMap<String, Object>();
            switch (i) {
                case 1:
                    item.put("imageItem", R.drawable.icon_juice);//添加图像资源的ID
                    item.put("textItem", "新鲜点");//按序号添加ItemText
                    items.add(item);
                    break;
                case 2:
                    item.put("imageItem", R.drawable.icon_flash);//添加图像资源的ID
                    item.put("textItem", "抢鲜啦！");//按序号添加ItemText
                    items.add(item);
                    break;
                case 3:
                    item.put("imageItem", R.drawable.icon_shake);//添加图像资源的ID
                    item.put("textItem", "摇一摇");//按序号添加ItemText
                    items.add(item);
                    break;
                case 4:
                    item.put("imageItem", R.drawable.icon_topup);//添加图像资源的ID
                    item.put("textItem", "充值有礼");//按序号添加ItemText
                    items.add(item);
                    break;
                case 5:
                    item.put("imageItem", R.drawable.home_order);//添加图像资源的ID
                    item.put("textItem", "物流·售后");//按序号添加ItemText
                    items.add(item);
                    break;
                case 6:
                    item.put("imageItem", R.drawable.redemption);//添加图像资源的ID
                    item.put("textItem", "提货券");//按序号添加ItemText
                    items.add(item);
                    break;
                case 7:
                    item.put("imageItem", R.drawable.enterprise);//添加图像资源的ID
                    item.put("textItem", "企业团购");//按序号添加ItemText
                    items.add(item);
                    break;
                case 8:
                    item.put("imageItem", R.drawable.icon_eattry);//添加图像资源的ID
                    item.put("textItem", "免费试吃");//按序号添加ItemText
                    items.add(item);
                    break;
            }
        }

        //实例化一个适配器
        SimpleAdapter adapter = new SimpleAdapter(getActivity(),
                items,
                R.layout.item_grideview,
                new String[]{"imageItem", "textItem"},
                new int[]{R.id.image_grideView, R.id.text_grideView});

        //获得GridView实例
         gv = (GridView) topView.findViewById(R.id.gridView);
        //为GridView设置适配器
        gv.setAdapter(adapter);
    }


    private void showRotation(View topView, Home home) {
        viewPager = (ViewPager) topView.findViewById(R.id.topViewPagerId);
        imageViews = new ArrayList<ImageView>();
        ImageView imageview = null;
        for (int i = 0; i < home.getRotation().size(); i++) {
            imageview = new ImageView(getActivity());
            imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageViews.add(imageview);
        }

        viewPager.setAdapter(new ViewPagerAdapter(imageViews));
        loadImgs(home);
        loopImgs();


    }


    private void loopImgs() {
        new Thread() {
            @Override
            public void run() {
                int i = 0;
                while (true) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i >= imageViews.size()) i = 0;

                    final int index = i++;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            viewPager.setCurrentItem(index);
                        }
                    });

                }
            }
        }.start();
    }

    private void loadImgs(Home home) {
        int i = 0;
        for (Banner top : home.getRotation()) {

            bUtils.display(imageViews.get(i), top.getPhoto());
            i++;
        }

    }


    private RequestParams getRquestParams() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("sign", "f8257b7dd195415f4ad65e851844b762");
        params.addBodyParameter("timestamp", "1434703913");
        params.addBodyParameter("platform", "ANDROID");
        params.addBodyParameter("source", "app");
        params.addBodyParameter("connect_id", "");
        params.addBodyParameter("region_id", "143949");
        params.addBodyParameter("service", "marketing.banner");
        params.addBodyParameter("device_id", "a781ff387d0fd135e5a97ed41f71838c");
        params.addBodyParameter("channel", "qq");
        params.addBodyParameter("version", "2.1.1");
        return params;


    }
}
